;
(function(factory) {
	layui.use(['layer', 'laypage', 'table', 'form'], function() {
		factory(jQuery, window, document, layui);
	});
}(function($, window, document, layui) {
	$(function() {
		funOp.init();
	});

	var funOp = {
		limit: 10,
		init: function() {

			$('#seach_submit').click(function() {
				funOp.queryMenu(1);
				return false;
			})

			funOp.tableInit();
			//funOp.selectParentMenu(0);
		},

		tableInit: function() {
			layui.table.render({
				elem: '#menu_table',
				toolbar: '#head_toolbar',
				limit: funOp.limit,
				cols: [
					[{
						title: '操作',
						fixed: 'left',
						toolbar: '#body_toolbar',
						width: 200
					}, {
						title: '序号',
						type: 'numbers',
						width: 50
					}, {
						field: 'name',
						title: '菜单名',
						width: 100
					}, {
						field: 'code',
						title: '菜单编码',
						width: 200
					}, {
						field: 'path',
						title: '路径',
						width: 150
					}, {
						field: 'icon',
						title: '图标',
						width: 200
					}, {
						field: 'hasNode',
						title: '是否有子级',
						width: 100
					}, {
						field: 'parentName',
						title: '父级菜单',
						width: 150
					}, {
						field: 'remark',
						title: '备注',
						// width: 200
					}]
				],
				data: []
			});

			layui.table.on('tool(menu_table)', function(obj) {
				var data = obj.data; //获得当前行数据
				var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
				var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

				if (layEvent === 'detail') {
					funOp.menuDeatil(data);
				} else if (layEvent === 'del') {
					layer.confirm('真的删除行么', function(index) {
						// obj.del();
						layer.close(index);
						funOp.deleteMenu(obj, data);
					});
				} else if (layEvent === 'edit') {
					layer.open({
						type: 1,
						title: '修改菜单',
						content: $('#editMenus').html()
					});
					var id= data.id;
					layui.form.val("edit", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
						"name": data.name // "name": "value"
						,"code": data.code
						,"path": data.path
						,"icon": data.icon
						,"has_node": data.hasNode
						,"parent_id": data.parentId
						,"level":data.level
						,"remark": data.remark
					});
					layui.form.on('submit(menuUpdateSubmit)',function (data) {
						funOp.editMenu(data.field,id);
					});

					layui.form.on('select(menuGrade1)',function (data) {
						//查父级
						funOp.selectParentMenu1(data.value-1,id);
						
					});
				}
			});

			layui.table.on('toolbar(menu_table)', function(obj) {
				console.info(obj);
				//var checkStatus = table.checkStatus(obj.config.id);
				switch (obj.event) {
					case 'add':
						layer.msg('添加');
						//打开新增弹窗
						layer.open({
							title: '新增菜单',
							type: 1,
							content: $('#addMenus').html()
						});
						layui.form.val("add", { 
							"has_node": 0
						});

						layui.form.on('submit(menuAddSubmit)',function (data) {
							funOp.addMenu(data.field);
						});

						layui.form.on('select(menuGrade)',function (data) {
							//查父级
							funOp.selectParentMenu(data.value-1);
							
						});

						
						break;
				};
			});
		},

		tableReload: function(pageIndex, total, data) {
			layui.table.reload('menu_table', {
				data: data
			});
			layui.laypage.render({
				elem: 'menu_page',
				limit: funOp.limit,
				curr: pageIndex,
				groups: 2,
				count: total,
				layout: ['count', 'prev', 'page', 'next'],
				jump: function(obj, first) {
					if (!first) {
						funOp.queryMenu(obj.curr);
					}
				}
			});

		},

		queryMenu: function(pageIndex) {
			var params = layui.form.val('seach_form');
			var where = ' where 0=0 ';
			var paramList = [];
			var pageParamList = [];
			$.each(params, function(key, value) {
				if (!value || value == '') {
					return true;
				}
				where += ' and ' + key + ' like concat("%", ? ,"%")';
				paramList.push(value);
			})
			where += ' and del_flag=0';
			pageParamList = paramList.concat([(pageIndex - 1) * funOp.limit, (pageIndex) * funOp
				.limit
			]);

			var c = 'SELECT count(0) num from menu ' + where;
			var s =
				'SELECT * , (select b.name from menu b where b.id = menu.parent_id ) parentName from menu ' +
				where + ' limit !,! ';

			var cObj = {
				sql: $.fn.commUtil.getSqlStr(c, paramList)
			}
			var sObj = {
				sql: $.fn.commUtil.getSqlStr(s, pageParamList)
			}
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(cObj),
				success: function(res) {
					console.info(res)
					if (res.code != 0 || res.data.length == 0 || res.data[0] == 0) {
						alert(res.msg);
						return;
					}
					var total = res.data[0].num;
					$.newAjax({
						url: $.fn.commUtil.constant.baseUrl + '/dealSql',
						data: JSON.stringify(sObj),
						success: function(res) {
							console.info(res)
							if (res.code != 0) {
								alert(res.msg);
								return;
							}
							funOp.tableReload(pageIndex, total, res.data);
						}
					});
				}
			});
		},

		menuDeatil: function(data) {
			//弹窗并赋值
			layer.open({
				type: 1,
				title: '查看菜单',
				content: $('#detailMenus').html()
			});
			layui.form.val("detail", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
				"name": data.name // "name": "value"
				,"code": data.code
				,"path": data.path
				,"icon": data.icon
				,"has_node": data.hasNode
				,"parent_id": data.parentName
				,"remark": data.remark
			});
		},

		addMenu: function(data) {
			var loginUser = $.fn.commUtil.getLoginUser();
			var username = loginUser.id;
			var paramList = [];
			var s = 'insert into menu ( ';
			$.each(data, function (key, value) {
				s += key + ',';
				paramList.push(value);
			})
			s+= ' del_flag,create_user) values (?,?,?,?,?,?,?,?,?,?)'
			paramList.push(0);
			paramList.push(username);
			var sqlObj = {
				sql: $.fn.commUtil.getSqlStr(s,paramList)
			}
			$.newAjax({
				url:$.fn.commUtil.constant.baseUrl+'/dealSql',
				data:JSON.stringify(sqlObj),
				success: function (res) {
					console.info(res);
					if(res.code!=0){
						alert(res.msg);
						return;
					}
					funOp.queryMenu(1);
				}
			})

		},

		editMenu: function(obj, data) {
			var paramList = [];
			var s = 'update menu set  ';
			$.each(obj, function (key, value) {
				if (!value || value == '') {
					return true;
				}
				s += key + '= ?,';
				paramList.push(value);
			});
			s = s.substring(0,s.length-1);
			s+= 'where id = ' + data;
			var sqlObj = {
				sql: $.fn.commUtil.getSqlStr(s,paramList)
			}
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data:JSON.stringify(sqlObj),
				success: function (res) {
					console.info(res);
					if(res.code!=0){
						alert(res.msg);
						return;
					}
					funOp.queryMenu(1);
				}
			})
		},

		deleteMenu: function(obj, data) {
			//
			//alert(data.id);
			var paramList = [];
			paramList.push(data.id);
			var delSql = 'update menu set del_flag=1 where id=?';
			var delRes = {
				sql: $.fn.commUtil.getSqlStr(delSql,paramList)
			}
			$.newAjax({
				url:$.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(delRes),
				success: function (res) {
					console.info(res)
					if(res.code!=0){
						alert(res.msg);
						return;
					}
					alert(res.msg);
				}
			})
			obj.del();
		},

		selectParentMenu: function (level) {
			var Sql = 'SELECT id , `name` from menu m where m.del_flag=0 and m.level='+level;
			var Res = {
				sql: $.fn.commUtil.getSqlStr(Sql)
			}
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(Res),
				success: function (res) {
					console.info(res)
					if (res.code != 0) {
						alert(res.msg);
						return;
					};
					//var h = [];
					$(".layui-layer-content [lay-filter='parentMenu']").empty();
					if(res.data.length==0){
						$(".layui-layer-content [lay-filter='parentMenu']").append("<option value='" + 0 + "'>" + "一级菜单默认选项" + "</option>");
					}
					
					$.each(res.data, function (i, n) {
						// funOp.roleList.push({
						// 	title: n.roleName,
						// 	id: n.id
						//   });
						$(".layui-layer-content [lay-filter='parentMenu']").append("<option value='" + n.id + "'>" + n.name + "</option>");
					})

					layui.form.render();

				}
			});
		},
		selectParentMenu1: function (level,id) {
			var Sql = 'SELECT id , `name` from menu m where m.del_flag=0 and  m.level='+level+' and m.id <>'+id;
			var Res = {
				sql: $.fn.commUtil.getSqlStr(Sql)
			}
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(Res),
				success: function (res) {
					console.info(res)
					if (res.code != 0) {
						alert(res.msg);
						return;
					};
					//var h = [];
					$(".layui-layer-content [lay-filter='parentMenu1']").empty();
					if(res.data.length==0){
						$(".layui-layer-content [lay-filter='parentMenu1']").append("<option value='" + 0 + "'>" + "一级菜单默认选项" + "</option>");
					}
					
					$.each(res.data, function (i, n) {
						// funOp.roleList.push({
						// 	title: n.roleName,
						// 	id: n.id
						//   });
						$(".layui-layer-content [lay-filter='parentMenu1']").append("<option value='" + n.id + "'>" + n.name + "</option>");
					})

					layui.form.render();

				}
			});
		}
	};
}));
